/**
 * Created by i-shaof on 8/11/14.
 */
if (!window.console) {
    window.console = {};
    window.console.log = function () {
    };
}
$.ajaxSetup({
	url:window.location.href,
    error:function (XMLHttpRequest, textStatus, errorThrown){
    	//console.log(XMLHttpRequest);
    	//console.log(textStatus);
    	//console.log(errorThrown);
    	//$.messager.progress('close');
    	var data=XMLHttpRequest.responseJSON
    	if(data){
    		$.messager.alert(errorThrown,+'errorCode:'+XMLHttpRequest.status+'<br />'+data.msg,'error');
    	}else{
    		$.messager.alert(errorThrown,+'errorCode:'+XMLHttpRequest.status+'<br />','error');
    	}
        
    },
	success:function(data, textStatus, jqXHR){
		//console.log(data);
		//console.log(textStatus);
		//console.log(jqXHR);
		//$.messager.progress('close');
		showMsg(0,'请求成功');
	}
});
$.fn.window.defaults.zIndex=100;
$.fn.datagrid.defaults.method='get';
var errormsg={
    0:"操作成功",
    500:"操作失败"
};
function showMsg(key,msg){
    $.messager.show({
        title:'我的消息',
        msg:errormsg[key]+'<br />'+msg,
        timeout:5000,
        showType:'slide'
    });
};
//全局默认配置
$.fn.datagrid.defaults.editid=-1;
$.fn.datagrid.defaults.multiple=true;
$.fn.datagrid.defaults.fit=true;
$.fn.datagrid.defaults.pagination=true;
$.fn.datagrid.defaults.singleSelect=true;
$.fn.datagrid.defaults.checkOnSelect=false;
$.fn.datagrid.defaults.selectOnCheck=false;
$.fn.datagrid.defaults.sortName='id',
$.fn.datagrid.defaults.sortOrder='desc',
//$.fn.datagrid.defaults.rownumbers=true,
$.fn.datagrid.defaults.edititem=[];
$.fn.datagrid.defaults.method='get';
$.fn.treegrid.defaults.editid=-1;
$.fn.treegrid.defaults.singleSelect=true,
$.fn.treegrid.defaults.checkOnSelect=false,
$.fn.treegrid.defaults.selectOnCheck=false,
$.fn.treegrid.defaults.edititem=[];
$.fn.treegrid.defaults.method='get';
$.fn.treegrid.defaults.fit=true,
$.fn.datagrid.defaults.editors.checkbox.setValue=function(aa,bb){
	
	var cc=false;
	if(bb){
		if($(aa).val()==bb.toString()){
			cc=true;
		}
	}
	
	$(aa)._propAttr("checked",cc);
};
$.fn.treegrid.methods.SaveData=function(jq,row){
	//$.messager.progress();
	var options=jq.treegrid('options');
    var rows=jq.treegrid('getChanges');
    var irows=jq.treegrid('getChanges','inserted');
    var erows=jq.treegrid('getChanges','updated');
    var drows=jq.treegrid('getChanges','deleted');
    if(rows.length==0){
    	$.messager.show({
    		title:'提示',
    		msg:'没有被更改的数据',
    		timeout:5000,
    		showType:'slide'
    	});
        return;
    }
    if(irows.length!=0){
        $.ajax({
            async:false,
            url:options.saveUrl,
            dataType:"json",
            type:'POST',
            data:JSON.stringify(irows),
            contentType: "application/json;charset=utf-8"
        });
    }
    if (erows.length!=0){
        $.ajax({
            async:false,
            type:'POST',
            url:options.editUrl,
            dataType:"json",
            data:JSON.stringify(erows),
            contentType: "application/json;charset=utf-8"
        });
    }
    if(drows.length!=0){
        var ids=[];
        $.each(drows,function(i,n){
            ids.push(n.id);
        });
        $.get(options.delUrl,{ids:ids.join(',')},function(data){

        },'json');
    }
    jq.treegrid('acceptChanges');
    if(callback){
        callback();
    }
}


/*$.fn.datagrid.defaults.onBeforeEdit=function(rowIndex,me){
    if(!me){
        me=$(this);
    }
    var options=me.datagrid('options');
    console.log('开始编辑:'+rowIndex);
    options.edititem.push(rowIndex);
};*/
$.fn.datagrid.methods.DelRows=function(jq){
	var rows=jq.datagrid('getChecked');
	if(rows.length==0){
		$.messager.alert('提示','请选择数据');
	}else{
		$.messager.confirm('确认','您确认想要删除'+rows.length+'记录吗？',function(r){
            if (r){
                var delurl=jq.datagrid('options').delUrl;
                var ids=[];
                $.each(rows,function(i,n){
                    ids.push(n.id);
                });
                $.get(delurl,$.param({ids:ids},true),function(data){
                	showMsg(0,'操作成功');
                	setTimeout(function(){jq.datagrid('reload')},1500);
                },'json');
            }
        });
	}
};
$.fn.datagrid.methods.addRow=function(jq,row){
	var options=jq.datagrid('options');
	if(!row){
		row={};
		row.id=options.editid--;
	}
    jq.datagrid('appendRow',row);
    editIndex=jq.datagrid('getRows').length-1;
    jq.datagrid('selectRow', editIndex)
        .datagrid('beginEdit', editIndex);
};
$.fn.datagrid.methods.RecChange=function(jq,datas){
    var options=jq.datagrid('options');
    var rows=jq.datagrid('getRows');
    $.each(options.edititem,function(i,n){
        if(datas){
        	$.each(datas,function(key,value){
        		//console.log(key);
        		//console.log(n);
                var ed=jq.datagrid('getEditor', {index:n,field: key});
                if(ed){
                	rows[n][value] = $(ed.target).combo('getText');
                }else{
                	console.log('未找到编辑器 info:[index:'+n+'field:'+key+']');
                }
                
            });
        }
        jq.datagrid('endEdit', n);
    });
    options.edititem=[];
};
function _datagrid_reload(jq){
	jq.datagrid('reload');
}
$.fn.datagrid.methods.SaveData=function(jq,callback_){
	//$.messager.progress();
    var options=jq.datagrid('options');
    var rows=jq.datagrid('getChanges');
    var irows=jq.datagrid('getChanges','inserted');
    var erows=jq.datagrid('getChanges','updated');
    var drows=jq.datagrid('getChanges','deleted');
    if(rows.length==0){
    	$.messager.show({
    		title:'提示',
    		msg:'没有被更改的数据',
    		timeout:5000,
    		showType:'slide'
    	});
        return;
    }
    if(irows.length!=0){
        $.ajax({
            async:false,
            url:options.saveUrl,
            dataType:"json",
            type:'POST',
            data:JSON.stringify(irows),
            contentType: "application/json;charset=utf-8"
        });
    }
    if (erows.length!=0){
        $.ajax({
            async:false,
            type:'POST',
            url:options.editUrl,
            dataType:"json",
            data:JSON.stringify(erows),
            contentType: "application/json;charset=utf-8"
        });
    }
    if(drows.length!=0){
        var ids=[];
        $.each(drows,function(i,n){
            ids.push(n.id);
        });
        $.get(options.delUrl,{ids:ids.join(',')},function(data){

        },'json');
    }
    //jq.datagrid('acceptChanges');
    //回调
    if(callback_){
    	callback_();
    }
    //$.messager.progress('close');
    setTimeout(function(){jq.datagrid('reload')},1500);
    
};
$.fn.datagrid.methods.CancelEdit=function(jq){
	var options=jq.datagrid('options');
	options.edititem=[];
	jq.datagrid('rejectChanges');
};
var msglist={
		text:'文本消息',
		news:'图文消息',
		image:'图片消息',
		voice:'语音消息',
		viceo:'视频消息',
		datas:undefined,
		getData:function(){
			if(this.datas){
				return this.datas;
			}
			var aa=[];
			$.each(this,function(i,n){
				if(typeof(n)=='string'){
					aa.push({label:n,value:i});
				}
			});
			return this.datas=aa;
		}
};
//$(function ($) {
//main_tab       主框架
    var $main_tab = $('#main_tab');
//west_accordion
    var $west_accordion = $('#west_accordion');


    var $weixin_tabs_contmenu=$('#weixin_tabs_contmenu');
    $west_accordion.accordion({
        multiple: false,
        fit: true
    });
    $weixin_tabs_contmenu.menu({
        onClick:function(item){
            console.log(item);
            var ttitle=$weixin_tabs_contmenu.menu('options').ttitle;
            switch (item.name)
            {
                case 'close':
                    $main_tab.tabs('close',ttitle);
                    break;
                case 'closeother':
                    var n=0;
                    while(true){
                        var tab=$main_tab.tabs('getTab',n);
                        if(tab){
                            var t=tab.panel('options').title;
                            if(t!=ttitle){
                                $main_tab.tabs('close',t);
                            }else{
                                n=1;
                            }
                        }else{
                            break;
                        }
                    }
                    break;
                case 'reload':
                    var title=$main_tab.tabs('getTab',ttitle).panel('options').title;
                    $main_tab.tabs('select',title);
                    setTimeout(refresh,200);
            }
        }
    });
    var url = 'menu/menus.json';
    $.post(url, function (data) {
        $.each(data, function (i, n) {
            $west_accordion.accordion('add', {
                content: '<ul style="padding: 5px 10px"></ul>',
                title: n.text,
                selected: i == 0
            });
            $west_accordion.accordion('getPanel', i).children().tree({
                data: n.children,
                animate: true,
                onClick: openTab
            });
        });
    }, 'json');
    $main_tab.tabs({
    	cache:false,
        iconAlign: 'right',
        fit: true,
        onContextMenu:function(e, title){
            e.preventDefault();
            $weixin_tabs_contmenu.menu('show', {
                left: e.pageX,
                top: e.pageY
            });
            $weixin_tabs_contmenu.menu('options').ttitle=title;
        }
    });
    var $window = $(window);
    var openTab = function (node) {
        var $tree=$(this);
        if ($tree.tree('isLeaf', node.target)) {
            var title = node.text;
            if ($main_tab.tabs("exists", title)) {
                $main_tab.tabs('select', title);
                return;
            }
            $main_tab.tabs('add', {
                iconCls: node.iconCls,
                title: title,
                href: node.url,
                closable: true,
                tools: [
                    {
                        iconCls: "icon-mini-refresh",
                        handler: refresh
                    }
                ],
                style: {
                    padding: 1
                }
            });
        }else{
            $tree.tree('toggle',node.target);
        }
        //console.log(node);
    };
    
    function refresh() {
        $main_tab.tabs('getSelected').panel('refresh');
    }
//});
    
    
    
    
    
    $.fn.panel.defaults.onBeforeDestroy=function(){
    	//console.log(this);
    	$(this).find('.combo-p').each(function(){
    		var panel = $(this).data().combo.panel;
    		console.log($(this).data());
			panel.panel("destroy");
    	});
    	$(this).find('.window-shadow').each(function(){
    		console.log('window');
    		console.log(this);
    	});
    }
    
    function destory(tmp){
    	if(tmp&&tmp.length>0){ 
    		console.log(tmp.data());
//tmp.window('destroy');
    		tmp.panel('destroy');
    	}
    	
    }